import React from 'react';
import { Modal } from 'antd-mobile';
import PickerHead from '../PickerHead';
import styles from './index.less';

function closest(el, selector) {
    const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    while (el) {
        if (matchesSelector.call(el, selector)) {
            return el;
        }
        el = el.parentElement;
    }
    return null;
}

const Popup = React.forwardRef(
    ({ title, children, content, cancelText = '取消', submitText = '确定', onCancel, onSubmit, ...rest }, ref) => {
        const [visible, setVisible] = React.useState(false);

        const onWrapTouchStart = e => {
            // fix touch to scroll background page on iOS
            if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
                return;
            }
            const pNode = closest(e.target, '.am-modal-content');
            if (!pNode) {
                e.preventDefault();
            }
        };
        return (
            <>
                <div onClick={() => setVisible(!visible)}>{children}</div>
                <Modal
                    ref={ref}
                    popup
                    visible={visible}
                    animationType="slide-up"
                    className={styles.customPopup}
                    wrapProps={{ onTouchStart: onWrapTouchStart }}
                    onClose={() => setVisible(false)}
                    {...rest}
                >
                    {title && (
                        <PickerHead
                            title={title}
                            onCancel={() => {
                                if (onCancel) {
                                    onCancel();
                                }
                                setVisible(false);
                            }}
                            onSubmit={() => {
                                if (onSubmit) {
                                    onSubmit();
                                }
                                setVisible(false);
                            }}
                            cancelText={cancelText}
                            submitText={submitText}
                        />
                    )}
                    <div className={styles.contentWrap}>{content}</div>
                </Modal>
            </>
        );
    }
);

export default Popup;
